const fs = require("fs");
const path = require("path");
const multer = require("multer");

const { findByPkBannerDao, updateBannerDao } = require("../dao/bannerDao");
const { ValidationError, UploadError } = require("../utils/error");
const { uploading, formatResponse } = require("../utils/tool");

module.exports.uploadImageService = async function (req, res, next) {
  const banner = await findByPkBannerDao(req.params.id);
  if (!banner) throw new ValidationError("banner is not exist");
  uploading.single("file")(req, res, async (err) => {
    if (err instanceof multer.MulterError) {
      next(new UploadError("上传文件失败，请检查文件的大小，控制在 2MB 以内"));
    } else if (err) {
      next(err);
    } else {
      const filePath = "/static/images/" + req.file.filename;
      if (!["midImg", "bigImg"].includes(req.body.field)) {
        fs.promises.unlink(path.join(__dirname, "../public", filePath));
        next(new ValidationError(`${req.body.field} field is not exist`));
      } else {
        const banner = await findByPkBannerDao(req.params.id);
        if (!banner) next(new ValidationError(`banner is not exist`));
        else {
          await updateBannerDao(req.params.id, {
            [req.body.field]: filePath,
          });
          fs.promises.unlink(
            path.join(__dirname, "../public", banner.dataValues[req.body.field])
          );
          res.send(
            formatResponse(0, "", {
              ...banner.dataValues,
              [req.body.field]: filePath,
            })
          );
        }
      }
    }
  });
};
